<script setup lang="ts">
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { getImg, projectCreateApi, projectEditApi } from '@/service/api/businessApi';
import { projectHooks } from '@/views/systemManage/projectManage/projectHooks';
import { localStg } from '@/utils/storage';
import cityData from '../staticData/city';

const { getProjectType } = projectHooks();
const token = localStg.get('token');
const projectTypeData = ref([]);

onMounted(async () => {
  projectTypeData.value = await getProjectType();
});

defineOptions({
  name: 'ProjectOperateDrawer'
});

interface Props {
  unitData: any;
  operateType: AntDesign.TableOperateType;
  rowData?: any | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<AntDesign.TableOperateType, string> = {
    add: '新增项目',
    edit: '编辑项目'
  };
  return titles[props.operateType];
});

const model: any = reactive(createDefaultModel());

function createDefaultModel(): any {
  return {};
}

const rules: any = {
  name: defaultRequiredRule,
  orgId: defaultRequiredRule,
  type: defaultRequiredRule,
  city: defaultRequiredRule
};

/** the enabled role options */
async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  imgPreview.value = '';
  if (props.operateType === 'edit' && props.rowData) {
    await nextTick();
    if (props.rowData.provinceCode) {
      model.city = [
        props.rowData.provinceCode.substring(0, 2),
        props.rowData.cityCode.substring(0, 4),
        props.rowData.countryCode
      ];
    }
    if (props.rowData.picName) {
      getImgPreview(props.rowData.picName);
    }
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  imgPreview.value = '';
  visible.value = false;
}

const doAddSubmit = async () => {
  if (model.city.length === 3) {
    model.provinceCode = `${model.city[0]}0000`;
    model.cityCode = `${model.city[1]}00`;
    model.countryCode = model.city[2];
  }
  const res = await projectCreateApi({
    ...model
  });
  if (res.error === null) {
    window.$message?.success('新增成功');
    closeDrawer();
    emit('submitted');
  }
};
const doEditSubmit = async () => {
  if (model.city.length === 3) {
    model.provinceCode = `${model.city[0]}0000`;
    model.cityCode = `${model.city[1]}00`;
    model.countryCode = model.city[2];
  }
  const res = await projectEditApi({
    ...model
  });
  if (res.error === null) {
    window.$message?.success('更新成功');
    closeDrawer();
    emit('submitted');
  }
};

const getImgPreview = async (fileName: any) => {
  getImg({
    fileName
  }).then((res: any) => {
    const reader = new FileReader();
    reader.onload = e => {
      imgPreview.value = e.target.result;
    };
    reader.readAsDataURL(res.data);
  });
};

const loading = ref(false);
const imgPreview: any = ref();
const uploadImgChange = (info: any) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    loading.value = false;
    model.picName = info.file.response.data;
    getImgPreview(info.file.response.data);
  }
  if (info.file.status === 'error') {
    loading.value = false;
    window.$message?.error('图片上传失败');
  }
};

const clearImage = () => {
  imgPreview.value = '';
  model.picName = '';
};

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add') {
    await doAddSubmit();
  }
  if (props.operateType === 'edit') {
    await doEditSubmit();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" :width="560" :mask-closable="false">
    <AForm ref="formRef" layout="vertical" :model="model" :rules="rules">
      <AFormItem label="项目名称" name="name">
        <AInput v-model:value="model.name" placeholder="请输入项目名称" />
      </AFormItem>
      <AFormItem label="所属单位" name="orgId">
        <ASelect
          v-model:value="model.orgId"
          :options="unitData"
          :field-names="{ label: 'name', value: 'id', options: 'options' }"
          placeholder="请选择所属单位"
        />
      </AFormItem>
      <AFormItem label="项目类型" name="type">
        <ASelect
          v-model:value="model.type"
          :options="projectTypeData"
          :field-names="{ label: 'name', value: 'id', options: 'options' }"
          placeholder="请选择项目类型"
        />
      </AFormItem>
      <AFormItem v-if="model.type === 1" label="项目地址" name="uri">
        <AInput v-model:value="model.uri" placeholder="请输入带http/https的地址,如https://baidu.com" />
      </AFormItem>
      <AFormItem label="省市区" name="city">
        <ACascader
          v-model:value="model.city"
          :options="cityData"
          :field-names="{ label: 'name', value: 'code', children: 'children' }"
          placeholder="请选择省市区"
        />
      </AFormItem>
      <AFormItem label="项目背景图" name="picName">
        <p style="padding-bottom: 8px">图片尺寸: 1920 * 1080</p>
        <AUpload
          v-model:file-list="model.fileList"
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="/api/file/upload"
          :headers="{
            authorization: token
          }"
          @change="uploadImgChange"
        >
          <div v-if="imgPreview" @click.stop>
            <AImage :src="imgPreview" alt="avatar" />
            <div>
              <a @click="clearImage">清除图片</a>
            </div>
          </div>
          <div v-else>
            <LoadingOutlined v-if="loading"></LoadingOutlined>
            <PlusOutlined v-else></PlusOutlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </AUpload>
      </AFormItem>
      <AFormItem label="详细地址" name="address">
        <AInput v-model:value="model.address" placeholder="请输入详细地址" />
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">取消</AButton>
        <AButton type="primary" @click="handleSubmit">确认</AButton>
      </ASpace>
    </template>
  </AModal>
</template>

<style scoped></style>
